package com.yunsoft.notice.service.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fld.central.common.model.code.BaseCode;
import com.fld.central.common.model.exception.SpiException;
import com.fld.platform.http.HttpClientMgrBean;
import com.fld.platform.http.HttpResult;
import com.fld.platform.http.ResultCode;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SmsManager implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsManager.class);

    private static final String APP_ID = "75163194649364831463";
    private static final String APP_KEY = "5bl96v6k2xmkoo811xjng6w2g6qg1e";
    /**验证码通知类短信*/
    private static final String SINGLE = "http://inner-sp-trade.1sapp.com/sms/single";
    /**营销短信*/
    private static final String BATCH = "http://inner-sp-marketing.1sapp.com/sms/batch";

//	private static final String APP_ID = "91549867429622478819";
//	private static final String APP_KEY = "z7kj4krxnp0rinhvmgq71s2mibhem9";
//	/**验证码通知类短信*/
//	private static final String SINGLE = "http://47.92.255.143/sms/single";
//	/**营销短信*/
//	private static final String BATCH = "http://47.92.255.143/sms/batch";


    private HttpClientMgrBean httpClient = HttpClientMgrBean.createInstance();

    private static final Map<String,String> RESULT_CODE = new HashMap<String,String>();
    static {
        RESULT_CODE.put("0", "成功");
        RESULT_CODE.put("1", "系统错误");
        RESULT_CODE.put("2", "http失败");
        RESULT_CODE.put("3", "系统错误");
        RESULT_CODE.put("7", "参数错误");
        RESULT_CODE.put("10", "黑名单中");
        RESULT_CODE.put("11", "找不到通道商");
        RESULT_CODE.put("12", "验签错误");
        RESULT_CODE.put("14", "通道商同步返回失败");
    }



    public static void main(String[] args) {
//		Map<String,String> params = new HashMap<String,String>();
//		params.put("month", "12");
//		params.put("day", "10");
//		params.put("week", "三");
//		params.put("amount", "12.35");
//
//		SMSTemplateCode templateCode = SMSTemplateCode.SMS_179216033;
//		String content = templateCode.getContent();
//		Set<String> keys = params.keySet();
//		for (String key : keys) {
//			content = content.replaceAll("\\$\\{"+key+"\\}", params.get(key));
//		}
//		System.out.println(content);

//        SMSMgrBean bean = new SMSMgrBean();
//		Map<String,String> params = new HashMap<String,String>();
//		params.put("code", "123654");
//		bean.publish(null, SMSTemplateCode.SMS_95550034, params, new String[] {"13554793093"});

//        bean.publish("13554793093", "生产短信测试"+System.currentTimeMillis());
//		List<String> phoneList = new ArrayList<String>();
//		phoneList.add("13554793093");
//		bean.publish("营销短信测试", phoneList);
    }


    /**
     * 生成前面
     * @param timestamp
     * @return
     */
    private String createSign(int timestamp) {
        return DigestUtils.md5Hex(APP_ID + APP_KEY + timestamp);
    }

    /**
     * 发送验证码或通知类短信，签名统一“库盒”
     * @param phone	-	接收手机号
     * @param content	-	短信内容
     * @return
     */
    public String publish(String phone,String content) throws SpiException {
        //
        if(content == null || "".equals(content.trim())) {
            throw new SpiException(BaseCode.ERROR,"短信内容为空");
        }
        if(phone == null || "".equals(phone.trim())) {
            throw new SpiException(BaseCode.ERROR,"手机号为空");
        }
        //
        if(content.contains("【库盒】")) {
            throw new SpiException(BaseCode.ERROR,"短信内容无需包含签名：【库盒】");
        }
        //
        int timestamp = (int)(System.currentTimeMillis()/1000);
        //
        Map<String,String[]> params = new HashMap<String,String[]>();
        params.put("app_id", new String[] {APP_ID});
        params.put("mobile", new String[] {phone});
        params.put("timestamp", new String[] {String.valueOf(timestamp)});
        params.put("sign", new String[] {createSign(timestamp)});
        params.put("content", new String[] {content});
        LOGGER.info("[发送通知类短信][发起请求][手机号：{}][参数：{}]",phone, JSON.toJSONString(params));
        HttpResult result = httpClient.post(SINGLE, params);
        LOGGER.info("[发送通知类短信][请求返回][手机号：{}][STATUS:{},CODE:{},MSG:{},DATA:{}]",phone,result.getCode(),result.getMsg(),result.getStatus(),result.getData());
        if(result.getCode().equals(ResultCode.SUCCESS.getCode()) &&	//http执行成功
                result.getStatus() == 200) {	//http返回200
            try {
                JSONObject obj = JSON.parseObject(result.getData());
                int code = obj.getIntValue("code");
                if(code == 0) {
                    return result.getData();
                }
                LOGGER.error("[发送通知类短信][接口返回异常][手机号：{}][错误码：{}][返回内容：{}]",phone,RESULT_CODE.get(String.valueOf(code)),result.getData());
                throw new SpiException(BaseCode.ERROR,String.format("[手机号：%s][错误码：%s][返回内容：%s]",phone,RESULT_CODE.get(String.valueOf(code)),result.getData()));
            } catch(Exception e) {
                LOGGER.error("[发送通知类短信][接口返回异常][手机号：{}][返回内容：{}]",phone,result.getData(),e);
                throw new SpiException(BaseCode.ERROR,String.format("[手机号：%s][返回内容：%s]",phone,result.getData()));
            }
        }
        throw new SpiException(BaseCode.ERROR,String.format("发送失败，HTTP Status：%s，返回内容：%s",result.getStatus(),result.getData()));
    }

    /**
     * <p>发送营销类短信，签名统一“库盒”</p>
     * <ul>
     * <li>1.签名为：【库盒】</li>
     * <li>2.签名统一为【库盒】，短信内容无需在添加</li>
     * <li>3.文案字符数限制65个字符，其中标点符号、空格、中文、英文分别算1个字符，尽量不要使用颜文字，不同emoji表情所占字符数不一样，通常2-4个字符数</li>
     * <li>4.链接前后分别保留1个空格</li>
     * <li>5.文案以 “回TD退订”结尾，短信内容无需在添加</li>
     * <li>6.下发时间限制08:00-20:00，其余时间不要下发</li>
     * </ul>
     * @param phoneList
     * @param content
     * @return
     */
    public String publish(List<String> phoneList, String content) throws SpiException {
        //
        if (content == null || "".equals(content.trim())) {
            throw new SpiException(BaseCode.ERROR, "短信内容为空");
        }
        if (phoneList == null || phoneList.isEmpty()) {
            throw new SpiException(BaseCode.ERROR, "手机号为空");
        }
        //
        if (content.contains("【库盒】")) {
            throw new SpiException(BaseCode.ERROR, "短信内容无需包含签名：【库盒】");
        }
        content = content + " 回复TD退订";
        //
        int timestamp = (int) (System.currentTimeMillis() / 1000);
        //
        StringBuilder builder = new StringBuilder("");
        for (String phone : phoneList) {
            builder.append(phone + ",");
        }
        builder.deleteCharAt(builder.length() - 1);

        Map<String, String[]> params = new HashMap<String, String[]>();
        params.put("app_id", new String[]{APP_ID});
        params.put("mobile", new String[]{builder.toString()});
        params.put("timestamp", new String[]{String.valueOf(timestamp)});
        params.put("sign", new String[]{createSign(timestamp)});
        params.put("content", new String[]{content});
        params.put("emoji_flg", new String[]{String.valueOf(0)});

        LOGGER.info("[发送营销类短信][发起请求][手机号：{}][参数：{}]", builder.toString(), JSON.toJSONString(params));
        HttpResult result = httpClient.post(SINGLE, params);
        LOGGER.info("[发送营销类短信][请求返回][手机号：{}][STATUS:{},CODE:{},MSG:{},DATA:{}]", builder.toString(), result.getCode(), result.getMsg(), result.getStatus(), result.getData());
        if (result.getCode().equals(ResultCode.SUCCESS.getCode()) &&    //http执行成功
                result.getStatus() == 200) {    //http返回200
            try {
                JSONObject obj = JSON.parseObject(result.getData());
                int code = obj.getIntValue("code");
                if (code == 0) {
                    return result.getData();
                }
                LOGGER.error("[发送营销类短信][接口返回异常][手机号：{}][错误码：{}][返回内容：{}]", builder.toString(), RESULT_CODE.get(String.valueOf(code)), result.getData());
                throw new SpiException(BaseCode.ERROR, String.format("[手机号：%s][错误码：%s][返回内容：%s]", builder.toString(), RESULT_CODE.get(String.valueOf(code)), result.getData()));
            } catch (Exception e) {
                LOGGER.error("[发送营销类短信][接口返回异常][手机号：{}][返回内容：{}]", builder.toString(), result.getData(), e);
                throw new SpiException(BaseCode.ERROR, String.format("[手机号：%s][返回内容：%s]", builder.toString(), result.getData()));
            }
        }
        throw new SpiException(BaseCode.ERROR, String.format("发送失败，HTTP Status：%s，返回内容：%s", result.getStatus(), result.getData()));
    }


}
